package com.kstech.ks_gaz01.fragments


import androidx.activity.OnBackPressedCallback
import androidx.navigation.Navigation
import androidx.recyclerview.widget.LinearLayoutManager
import com.blankii.androidlibrary.base.BaseBindingFragment
import com.blankii.androidlibrary.exts.logd
import com.blankii.androidlibrary.exts.loge
import com.blankii.androidlibrary.views.DividerItemDecoration
import com.kstech.ks_gaz01.R
import com.kstech.ks_gaz01.XML_ADDRESS_SAVE_PARAM
import com.kstech.ks_gaz01.data.ReadFileAdapter
import com.kstech.ks_gaz01.databinding.FragmentReadfileBinding
import com.kstech.ks_gaz01.debug
import com.kstech.ks_gaz01.getFileBasePath
import com.kstech.ks_gaz01.manager.ExcelManager
import com.kstech.ks_gaz01.socket.SocketFragmentListener
import com.kstech.ks_gaz01.socket.SocketManagerNew
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.io.File

/**
 * author: blankii
 * created on: 2024/4/29 15:56
 * description: 写入文件界面   读取本地excel文件，并一次性写入控制器
 */
class ReadFileFragment :
    BaseBindingFragment<FragmentReadfileBinding>(FragmentReadfileBinding::inflate),
    SocketFragmentListener {

    private lateinit var readFileAdapter: ReadFileAdapter
    private lateinit var excelList: ArrayList<ExcelManager.ExcelBean>
    private var filePosition = -1
    private var workStatus = true
    private val files = ArrayList<String>()
    private var stopSend = true
    private var readItemCount = 0
    private var nextTag = true
    private var lastReadFilePosition = 0
    private var reSendCount = 0


    override fun onCreateInit() {
        SocketManagerNew.startSendFault = false
        /**
         * 拦截返回按键
         */
        activity?.onBackPressedDispatcher?.addCallback(this, object : OnBackPressedCallback(true) {
            override fun handleOnBackPressed() {
                if (!stopSend) {
                    isEnabled = true
                    "正在写入数据中，请稍等".showSnackBar()
                } else {
                    isEnabled = false
                    activity?.onBackPressed()
                }
            }
        })
    }


    override fun onInitView() {
        SocketManagerNew.subscribeSocketFragmentListener(this@ReadFileFragment)
        workStatus = true

        initData()
        initView()
    }

    private fun initView() {
        binding.openFile.setOnClickListener { it ->
            if (filePosition == -1) {
                "请选择其中一项".showSnackBar()
                return@setOnClickListener
            }
            /**
             * 开始写入文件或者重新写入文件，重置状态
             */
            stopSend = false
            readItemCount = 0
            nextTag = true
            readItemCount = 0
            CoroutineScope(Dispatchers.Main).launch {
                withContext(Dispatchers.IO) {
                    //给debugData-parentList 赋值
                    excelList = ExcelManager.readExcel(files[filePosition])
                    binding.progressBar.max = excelList.size
                    requireActivity().runOnUiThread {
                        "需要写入数据个数:${excelList.size},正在写入请稍等".showSnackBar()
                    }

                    //按顺序发给控制器
                    while (workStatus) {
                        if (!stopSend && nextTag && readItemCount < excelList.size) {
                            reSendCount = 0
                            nextTag = false
                            lastReadFilePosition = readItemCount
                            val msg = SocketManagerNew.sendWriteMsg(
                                excelList[readItemCount].address,
                                excelList[readItemCount].value,
                                excelList[readItemCount].isNegativeNumber
                            )
                            msg.loge(TAG)
//                            Log.e(
//                                "readFile",
//                                "发送：address:${excelList[readItemCount].address},value:${excelList[readItemCount].value},isNegativeNumber:${excelList[readItemCount].isNegativeNumber}"
//                            )
//                            "发送position:${readItemCount} 地址:${excelList[readItemCount].address},值：${excelList[readItemCount].value}".logd(
//                                TAG
//                            )
                            if (debug) {
                                writeSuccess(
                                    excelList[readItemCount].address, excelList[readItemCount].value
                                )
                            }
                        }
                        if (reSendCount > 30) {
                            /**
                             *重新发送
                             */
                            nextTag = true
                            readItemCount = lastReadFilePosition
                            "重新准备发送position:${readItemCount}".logd(TAG)
                        }
                        reSendCount++
                        delay(50)
                    }
                }
            }
        }
    }

    private fun initData() {
        CoroutineScope(Dispatchers.Main).launch {
            files.clear()
            withContext(Dispatchers.IO) {
                val path = getFileBasePath()
                if (File(path).exists()) {
                    File(path).listFiles().forEach {
                        if (it.name.contains("xls")||it.name.contains("xlsx")) {
                            files.add(it.name.toString())
                        }
                    }
                } else {
                    "/hzaichi/文件路径不存在".showSnackBar()
                }
            }

            binding.apply {
                recyclerView.layoutManager = LinearLayoutManager(requireActivity())
                recyclerView.addItemDecoration(
                    DividerItemDecoration(
                        requireActivity(), R.color.background_logoBar
                    )
                )
                readFileAdapter = ReadFileAdapter()
                readFileAdapter.setOnItemClickListener { adapter, view, position ->
                    filePosition = position
                    readFileAdapter.clickPosition(position)
                    readFileAdapter.notifyDataSetChanged()


                }
                recyclerView.adapter = readFileAdapter
                readFileAdapter.submitList(files)
                readFileAdapter.notifyDataSetChanged()
            }
        }
    }

    /**
     * 给某个地址  发送一个值
     * 控制器 回应该地址
     */
    override fun writeSuccess(address: String, value: String) {
        if (XML_ADDRESS_SAVE_PARAM == "4$address") {
            requireActivity().runOnUiThread {
                val navController = Navigation.findNavController(binding.root)
                navController.navigateUp()
                "写入成功".showSnackBar()
                return@runOnUiThread
            }
        } else if (!debug && readItemCount < excelList.size && excelList[readItemCount].address != "4$address") {
            stopSend = true
            "Excel文件中不存在该地址${address},${excelList[readItemCount].itemName} 写入异常,已终止写入".showSnackBar()
        } else {
            readItemCount++
            binding.progressBar.progress = readItemCount
            nextTag = true
//            "接收：address:$address,value:${value}".logd(TAG)
            if (readItemCount >= excelList.size) {
                stopSend = true
                /**
                 * 发送43705  0x5A5A
                 * 参数保存成功
                 */
                SocketManagerNew.sendWriteMsg(XML_ADDRESS_SAVE_PARAM, "23130")
            }
        }
    }

    override fun readSuccess(address: String, result: ArrayList<String>) {

    }

    override fun onDestroyView() {
        super.onDestroyView()
        workStatus = false
        SocketManagerNew.startSendFault = true
    }
}